import { SpaceInfoEntity } from './../entity/info';
import { Config, Provide } from '@midwayjs/decorator';
import { BaseService, CoolFileConfig, MODETYPE } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository, In } from 'typeorm';
const fs = require('fs');
const path = require('path');

/**
 * 文件信息
 */
@Provide()
export class SpaceInfoService extends BaseService {
  @InjectEntityModel(SpaceInfoEntity)
  spaceInfoEntity: Repository<SpaceInfoEntity>;

  @Config('cool.file')
  config: CoolFileConfig;

  /**
   * 新增
   */
  async add(param) {
    if (this.config.mode == MODETYPE.LOCAL) {
      param.key = param.url.replace(this.config.domain, '');
    }
    return super.add(param);
  }

  async deleteCustom(ids) {
    const fileds = await this.spaceInfoEntity.find({
      where: {
        id: In(ids),
      },
    });

    if (fileds) {
      const fileDir = fileds?.[0].key;
      const dir = fileDir.substring(0, fileDir.lastIndexOf('/'));

      const directoryPath = path.join(this.baseApp.getBaseDir(), '..', dir);
      const fileNamesArray = fileds.map(v => `${v.fileId}_${v.name}`);
      fs.readdir(directoryPath, (err, files) => {
        if (err) {
          console.error('Error reading directory:', err);
          return;
        }

        files.forEach(file => {
          if (fileNamesArray.includes(file)) {
            const filePath = `${directoryPath}/${file}`;
            fs.unlink(filePath, err => {
              if (err) {
                console.error('Error deleting file:', err);
              } else {
                console.log('File deleted:', filePath);
              }
            });
          }
        });
      });
    }

    return await this.spaceInfoEntity.delete(ids);
  }
}
